// 检查全局axios是否可用
let axios = window.axios;

// 如果全局axios不可用，尝试动态加载
if (!axios || typeof axios.post !== 'function') {
    console.log('全局axios不可用，尝试动态加载');
    
    // 动态加载axios的函数
    function loadAxios() {
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js';
            script.onload = () => {
                console.log('axios加载成功');
                resolve(window.axios);
            };
            script.onerror = (err) => {
                console.error('加载axios失败:', err);
                reject(err);
            };
            document.head.appendChild(script);
        });
    }
    
    // 尝试加载axios
    loadAxios().then(loadedAxios => {
        axios = loadedAxios;
        console.log('axios动态加载成功');
    }).catch(err => {
        console.error('动态加载axios失败:', err);
    });
}

const url = 'https://api.powerbi.com/beta/e96fa72b-c8d6-4957-96bd-c7f8dc30cc88/datasets/31fb02b8-3e95-4bec-b9b2-5af9c0d67aa0/rows?experience=power-bi&key=28Ri5RxnC5wvZFax5umuUDI2FZi6LxZ6q1bZPLqtfNfSXkLIuxqvge6bkETamwjdYIo%2F0EP8sgoAVzi55wI2Dw%3D%3D';

// 使用浏览器原生fetch API发送请求的备用方法
async function sendWithFetch(data) {
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
        });
        
        const responseData = await response.text();
        console.log('status code：', response.status);
        console.log('respose data：', responseData);
        
        return {
            status: response.status,
            data: responseData
        };
    } catch (error) {
        console.error('Fetch error:', error);
        throw error;
    }
}

async function sendMonitoringData(data) {
    try {
        console.log('sending pbi data:', data);
        
        // 再次检查axios是否有效
        if (axios && typeof axios.post === 'function') {
            // 使用axios发送请求
            const response = await axios.post(url, data);
            console.log('status code：', response.status);
            console.log('respose data：', response.data);
            return { success: true, message: '监控数据发送成功' };
        } else {
            // 使用备用方法发送请求
            console.log('axios无效，使用浏览器原生fetch API发送请求');
            const response = await sendWithFetch(data);
            return { success: true, message: '监控数据发送成功(使用备用方法)' };
        }
    } catch (error) {
        console.error('Error sending monitoring data:', error.message);
        let errorMessage = '监控数据发送失败';
        if (error.response) {
            console.error('Response status:', error.response.status);
            console.error('Response data:', error.response.data);
            errorMessage += `: 服务器响应错误 (${error.response.status})`;
        } else if (error.request) {
            console.error('No response received:', error.request);
            errorMessage += ': 未收到服务器响应，可能是网络问题';
        } else {
            console.error('Error setting up the request:', error.message);
            errorMessage += `: ${error.message}`;
        }
        return { success: false, message: errorMessage };
    }
}

// 通过全局对象直接导出函数，以便在浏览器环境中使用
window.sendMonitoringData = sendMonitoringData;
